<?php
class ControllerPaymentPagSeguro extends Controller {
	protected function index() {
    	$this->data['button_continue'] = $this->language->get('button_continue');
		$this->data['button_back'] = $this->language->get('button_back');

	if (!$this->config->get('pagseguro_test')) {
    		$this->data['action'] = 'https://pagseguro.uol.com.br/checkout/checkout.jhtml';
  		} else {
			$this->data['action'] = 'https://pagseguro.uol.com.br/checkout/checkout.jhtml';
		}		
				
		$this->load->model('checkout/order');
			
		$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
		
		
		$this->load->library('encryption');
		
		$codigoencip=$this->config->get('config_encryption');
		
		if(isset($codigoencip)){
		$encryption = new Encryption($codigoencip);
		}else {	
		$encryption = new Encryption($this->config->get('pagseguro_encryption'));	
		}
		
		$this->data['business'] = $this->config->get('pagseguro_email');
		$this->data['item_name'] = $this->config->get('config_store');				
		$this->data['currency_code'] = $order_info['currency'];
		$this->data['amount'] = $this->currency->format($order_info['total'], $order_info['currency'], $order_info['value'], FALSE);
		
		$this->data['first_name'] = $order_info['payment_firstname'];
		$this->data['last_name'] = $order_info['payment_lastname'];
		$this->data['address1'] = $order_info['payment_address_1'];
		$this->data['address2'] = $order_info['payment_address_2'];
		if(isset($order_info['payment_numero'])){
		$this->data['numero'] = $order_info['payment_numero'];
		}
		if(isset($order_info['payment_bairro'])){
		$this->data['bairro'] = $order_info['payment_bairro'];
		}
		$this->data['city'] = $order_info['payment_city'];
		$this->data['zip'] = $order_info['payment_postcode'];
		$this->data['country'] = $order_info['payment_country'];
		$this->data['notify_url'] = HTTP_SERVER . 'index.php?route=payment/pagseguro/callback&order_id=' . $encryption->encrypt($this->session->data['order_id']);
		$this->data['codipedido'] = $encryption->encrypt($this->session->data['order_id']);
		$this->data['email'] = $order_info['email'];
		$this->data['invoice'] = $this->session->data['order_id'] . ' - ' . $order_info['payment_firstname'] . ' ' . $order_info['payment_lastname'];
		
		//pega id do pais		
$this->load->model('localisation/country');
		
    	$paises = $this->model_localisation_country->getCountries();		
		
		foreach ($paises as $country) {
			if($country['name']==$order_info['payment_country']){
				
				$codigodopais = $country['country_id'];
				
			}
			
		}
//com id do pais pega cod da cidade
$this->load->model('localisation/zone');

    	$results = $this->model_localisation_zone->getZonesByCountryId($codigodopais);

foreach ($results as $result) {
        	if($result['name']==$order_info['payment_zone']){
				$this->data['estado'] =$result['code'];
			}

    	} 
		
		if(isset($order_info['ddd'])){
		$this->data['ddd'] = $order_info['ddd'];
		}else{
		$ntelefone = preg_replace("/[^0-9]/", "", $order_info['telephone']);	
			if(strlen($ntelefone) >= 10){	
				$ntelefone = ltrim($ntelefone, "0");
				$this->data['ddd'] = substr($ntelefone, 0, 2);
				$this->data['telephone'] = substr($ntelefone, 2,11);
			}
			else{
				$this->data['telephone'] = substr($ntelefone, 2,11);
			}
		}

$this->data['mailpg'] = $this->config->get('pagseguro_email');
		
			if (isset($this->session->data['coupon'])) {
			$this->load->model('checkout/coupon');
		
			$coupon = $this->model_checkout_coupon->getCoupon($this->session->data['coupon']);
			
			if(isset($coupon)){	
			
		$trancaproduto=1;
			$restocupom=$coupon['discount'];
			 if($coupon['shipping']==1){
					
					$this->data['fretegratis'] = true;
					
				}
		
		}
			
				
			} 
			
			$this->data['products'] = array();
			
			foreach ($this->cart->getProducts() as $product) {
			$option_data = array();
			
			foreach ($product['option'] as $option) {
        		$option_data[] = array(
          			'name'  => $option['name'],
          			'value' => $option['value']
        		);
      		} 
			
		if(isset($coupon)){	
		if($coupon['type']=='P'){
					$valorddescon = ($restocupom/100)*$product['price'];
					$valorproduto=($product['price']-$valorddescon);
					
				}else if($coupon['type']=="F"){
					if($trancaproduto==1){
					if($restocupom<=$product['price']){
					$valorproduto=($product['price']-$restocupom);
					$trancaproduto=2;
					}
					else {
					$restocupom=($restocupom-$product['price']);	
					$valorproduto=0;
					}
					}else {
						
					$valorproduto=$product['price'];
					}
				}
				
			}else {	
				$valorproduto=$product['price'];
		
		}
			
			
		
		$this->data['products'][] = array(
				'descricao'       => $product['name'],
				'valor'      => $this->currency->format($this->tax->calculate($valorproduto, $product['tax_class_id'], $this->config->get('config_tax'))),
				'quantidade'   => $product['quantity'],
				'option'     => $option_data,
				'id' => $product['product_id'],	
				'peso' => $this->weight->convert($product['weight'], $product['weight_class_id'], $this->config->get('config_weight_class_id'))
      		); 
    	} 
		
		
		//fim
		
			$this->data['return'] = HTTPS_SERVER . 'index.php?route=checkout/success';

if ($this->request->get['route'] != 'checkout/guest_step_3') {
			$this->data['cancel_return'] = HTTPS_SERVER . 'index.php?route=checkout/payment';
		} else {
			$this->data['cancel_return'] = HTTPS_SERVER . 'index.php?route=checkout/guest_step_2';
		}
		
		

		$this->data['continue'] = HTTPS_SERVER . 'index.php?route=checkout/success';
		
		if ($this->request->get['route'] != 'checkout/guest_step_3') {
			$this->data['back'] = HTTPS_SERVER . 'index.php?route=checkout/payment';
		} else {
			$this->data['back'] = HTTPS_SERVER . 'index.php?route=checkout/guest_step_2';
		}
		
		
		
		$this->id = 'payment';

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/pagseguro.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/payment/pagseguro.tpl';
		} else {
			$this->template = 'default/template/payment/pagseguro.tpl';
		}	
		
		$this->render();	
				
	}

	
	public function confirm() {
			$this->load->language('payment/pagseguro');
		$this->load->model('checkout/order');
		
		//$this->load->library('encryption');
		
		//$encryption = new Encryption($this->config->get('config_encryption'));
		
		//$codigopedido = $encryption->encrypt($this->session->data['order_id']);
		
		$comment  = $this->language->get('text_instruction') . "\n\n";
		//$comment .= $this->language->get('text_linkpagueseguro').$codigopedido.$this->language->get('text_linkpagueseguro'). "\n\n";
		$comment .= $this->language->get('text_payment');
		
		$this->model_checkout_order->confirm($this->session->data['order_id'], $this->config->get('config_order_status_id'), $comment);
		
		if (isset($this->session->data['order_id'])) {
			$this->cart->clear();
			
			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
			unset($this->session->data['payment_method']);
			unset($this->session->data['payment_methods']);
			unset($this->session->data['comment']);
			unset($this->session->data['order_id']);	
			unset($this->session->data['coupon']);
		}
	}
	
	public function callback() {
		if (isset($this->request->post['Token']) AND isset($this->request->post['Referencia'])){
			
		/*$data = array();
		
		foreach ($this->request->post as $key => $value) {
			$data[$key] = $value; //urldecode(stripslashes($value));
		}*/
		
		$this->load->language('payment/pagseguro');
		
		$reference = $this->request->post['Referencia'];
			
		$this->load->library('encryption');
		$codigoencip=$this->config->get('config_encryption');
		if(isset($codigoencip)){
		$encryption = new Encryption($codigoencip);
		}else {	
		$encryption = new Encryption($this->config->get('pagseguro_encryption'));	
		}
		
		$reference = $encryption->decrypt($reference);
		
		$this->load->model('checkout/order');
				
		$order_info = $this->model_checkout_order->getOrder($reference);
		
		 if ($this->request->post['Token'] == $this->config->get('pagseguro_encryption')) {
 

      if ($order_info) {
		  $this->cart->clear();
       
      if ($this->request->post['StatusTransacao'] == 'Aguardando Pagto') {
        // recupera código do status aguardando pagto
     
          $aguardando = $this->config->get('pagseguro_aguardando');
		  
$comentaraio=sprintf($this->language->get('text_aguardandopg'), $this->request->post['TipoPagamento']).$this->language->get('text_auterastatus');
		  
		   // atualiza status do pedido
		 // atualiza historico do pedido
	$this->model_checkout_order->update((int)$reference, (int)$aguardando, $comentaraio,true);
     
$this->model_checkout_order->confirm((int)$reference,(int)$aguardando, $comentaraio);

      }
      elseif ($this->request->post['StatusTransacao'] == 'Cancelado') {
        // recupera código do status em cancelado
		 $cancelado = $this->config->get('pagseguro_cancelado');
		 
$comentaraio=sprintf($this->language->get('text_canceladouol'), $this->request->post['TipoPagamento']).$this->language->get('text_auterastatus');
		  // atualiza status do pedido
		// atualiza historico do pedido
	$this->model_checkout_order->update((int)$reference, (int)$cancelado, $comentaraio,true);
		
      $this->model_checkout_order->confirm((int)$reference,(int)$cancelado, $comentaraio);
																											 
      }
      elseif ($this->request->post['StatusTransacao'] == 'Aprovado') {
        // recupera código do status aprovado
          $aprovado = $this->config->get('pagseguro_aprovado');
		  
$comentaraio=sprintf($this->language->get('text_aprovandouol'), $this->request->post['TipoPagamento']).$this->language->get('text_auterastatus');
		   // atualiza status do pedido
		// atualiza historico do pedido
$this->model_checkout_order->update((int)$reference, (int)$aprovado, $comentaraio,true);
		
 $this->model_checkout_order->confirm((int)$reference,(int)$aprovado, $comentaraio);
        
      }
	  
	//nao parece para o cli
	elseif ($this->request->post['StatusTransacao'] == 'Em Análise') {
        // recupera código do status aprovado
          $aguardando = $this->config->get('pagseguro_aguardando');
		  
$comentaraio=sprintf($this->language->get('text_aprovemanalize'), $this->request->post['TipoPagamento']).$this->language->get('text_auterastatus');

$this->model_checkout_order->update((int)$reference, (int)$aguardando, $comentaraio);
		
        
      }
	  
	elseif ($this->request->post['StatusTransacao'] == 'Completo') {
        // recupera código do status aprovado
          $aguardando = $this->config->get('pagseguro_aguardando');
		  
$comentaraio=sprintf($this->language->get('text_pagcompleto'), $this->request->post['TipoPagamento']).$this->language->get('text_auterastatus');

$this->model_checkout_order->update((int)$reference, (int)$aguardando, $comentaraio);
		
        
      }	  
	  
	  
	  
	  }
	  
	  }
	  
	  }
	  
	  }
}
 
?>